package com.ds.api.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ds.api.dao.SendMessageLogMapper;
import com.ds.api.model.SendMessageLogInfo;
import com.ds.api.utils.StringUtil;
import com.ds.api.utils.message.SendMessageUtil;
import com.ds.api.utils.message.SmsSingleSenderResult;
import com.google.gson.Gson;
/**
 * 发送信息
 * @className: SendMessageController
 * @description: TODO
 * @author xiangwei
 */
@Controller
@RequestMapping("/send")
public class SendMessageController extends BaseController {
    private static final Logger log = LoggerFactory
            .getLogger(SendMessageController.class);
    
    @Autowired
    private SendMessageLogMapper logmapper;
    
    @RequestMapping(value = "/message")
    public void getCustomerByParentId(@RequestParam Map<String,Object> param,
            HttpServletRequest request, HttpServletResponse response) {
        try {
            String randomNum = (int) (Math.random() * 100000) + "";
            if (randomNum.length() < 4) {
                randomNum = StringUtil.lpad(4, randomNum);
            }
            if (randomNum.length() > 4) {
                randomNum = randomNum.substring(0, 4);
            }
            
            Map<String, Object> result = new HashMap<String, Object>();
            String phone=param.get("mobile_phone")+"";
            SmsSingleSenderResult smsresult= SendMessageUtil.sendMessage(phone, randomNum);
            if(smsresult.result==0) {
            	SendMessageLogInfo info=new SendMessageLogInfo();
            	info.setPhone(phone);
            	info.setCreateAt(new Date());
            	info.setContent(randomNum);
            	info.setResult("您的验证码是"+randomNum);
            	info.setSendStatus("0");
            	info.setSendAt(new Date());
            	logmapper.insert(info);
            }else {
                result.put("err_str", "短信发送失败");

            }
            result.put("result", smsresult.result);
            response.setCharacterEncoding("utf-8");
            Gson gson = new Gson();
            response.getWriter().println(gson.toJson(result));
        } catch (Exception ex) {
            log.error("获取短信接口失败:{}", ex);
        }
    }
}
